/*
 * @Description: 
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2023-03-27 17:08:18
 */
import './index.scss'
import { DownOutlined, } from "@ant-design/icons";
import { Select, Tree, } from "antd";
import { useEffect, useRef, useState } from "react";
import 'highlight.js/styles/atom-one-dark.css'

const Backend = () => {
  const [treeData, setTreeData] = useState([])
  const [projectList, setProjectList] = useState<{ label: string, value: string }[]>([])
  const ref = useRef(null)
  const codeRef = useRef(null)

  useEffect(() => {
    // 获取文件
    http.post<{ label: string, value: string }[]>('/onlineEditor').then(res => {
      setProjectList(res.data)
    })

  }, [])



  /**获取单个项目树 */
  const getProjectTree = (path: string) => {
    http.post<any>('/onlineEditor/getFileTree', { path }).then(res => {
      setTreeData(res.data)
    })
  }

  /**获取单个文件内容 */
  const getFile = (path: string) => {
    http.post<string>('/onlineEditor/getFile', { path }).then(res => {
      (codeRef.current as any).innerHTML = res.data
    })
  }

  const onSelect = (selectedKeys: any, info: any) => {
    if (info.node.type === 'file') {
      getFile(info.node.value)
    }

  };

  return (
    <div ref={ref} className='backend'>
      <div className="left-tree">
        <div className="project-list">
          <Select
            style={{ width: 300 }}
            onChange={getProjectTree}
            showSearch
            options={projectList}
            placeholder="请选择项目"
          />
        </div>
        <Tree
          switcherIcon={<DownOutlined />}
          onSelect={onSelect}
          treeData={treeData}
        />
      </div>
      {
        treeData.length > 0 && (
          <div className="json">
            <pre contentEditable id="code" ref={codeRef} />
          </div>
        )
      }
    </div >
  );
};

export default Backend;